<template>
  <div
    style="position:fixed;right: 20px;top:120px;background-color: rgba(233, 224, 144, 0.205); border:1px solid #123123;z-index: 100;"
  >
    <div></div>
    <!--目录导航-->
    <div
      v-for="(anchor, index) in titles"
      :key="index"
      :style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
      style="cursor: pointer"
      @click="handleAnchorClick(anchor)"
    >
      <!--目录连接-->
      <a style="cursor: pointer">{{ anchor.title }}</a>
    </div>
  </div>
  <!--文档部分-->
  <v-md-preview
    ref="preview"
    :text="current.docInfo.md"
    preview-class="vuepress-markdown-body"
    :height="editHeight+'px'"
  >
  </v-md-preview>
  <!--可运行代码-->
  <my-code
    :docInfo="current.docInfo"
  ></my-code>
   
</template>

<script>
  import { reactive, ref, watch, onMounted } from 'vue'
  import mdController from '../service/md.js'
  import myCode from '../runCode/code.vue'
  // 目录连接
  import myList from './md-catalogue.vue'

  // 状态
  import { state } from '@naturefw/nf-state'

</script>

<script setup>
  
  const props = defineProps({
    // current: Object
  })
  const current = state.current // props.current

  // 可见的高度
  const editHeight = document.documentElement.clientHeight - 200
  const { loadDocById } = mdController()


  const preview = ref(null)
  const titles = reactive([])

  let anchors = null

  const setAnchors = () => {
    anchors = preview.value.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
    titles.push(...Array.from(anchors).filter((title) => !!title.innerText.trim()))

    if (!titles.length) {
      titles.length = 0
    }

    const hTags = Array.from(new Set(titles.map((title) => title.tagName))).sort();

    titles.push(
      ...titles.map((el) => {
        if (typeof el.getAttribute === 'function') {
          return {
            title: el.innerText,
            lineIndex: (el.getAttribute)? '' : el.getAttribute('data-v-md-line'),
            indent: hTags.indexOf(el.tagName),
          }
        }
      })
    )
  }

  onMounted(() => {
    setAnchors()
  })

  // 
  watch(() => current.menuId, (id) => {
    setTimeout(() => {
      titles.length = 0
      setAnchors()
    }, 100)
  })

  const handleAnchorClick = (anchor) => {
    const { lineIndex } = anchor

    const heading = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`)

    if (heading) {
      preview.value.scrollToTarget({
        target: heading,
        scrollContainer: window,
        top: 60
      })
    }
  }

</script>